<template>
  <div :class="show?'page':'page1'">
    <!-- 商品图片展示部分 -->
    <div class="header">
      <swiper class="swiper-box" autoplay @change="swiperChange">
        <swiper-item
          v-for="(item,index) of goodsInfo.bannerImgPaths"
          :key="index"
          class="swiper-item"
          :data-index="index"
        >
          <div class="image-box">
            <image :src="item" class="slide-image" :style="{height:height+'px'}" />
          </div>
        </swiper-item>
      </swiper>
      <span class="position">
        <span style="font-size:18px;margin-right:2px;">{{swiperIndex}}</span>
        <span>/</span>
        {{goodsInfo.bannerImgPaths.length}}
      </span>
    </div>

    <!-- 主体部分 -->
    <div class="main">
      <div class="details">
        <p class="det-title">{{goodsInfo.goodsName}}</p>
        <p class="det-mun">
          <span class="det-left">
            {{goodsInfo.salePrice}}
            <span style="font-size: 14px;">积分</span>
          </span>
        </p>
      </div>

      <div class="photo">
        <div v-html="richText"></div>
      </div>
    </div>

    <!-- 商品规格部分 -->
    <div v-if="show" class="show" @click="closeDialog">
      <div class="speci-content" @click.stop="showDialog">
        <div class="head-box">
          <img :src="goodsSku.skuImg||goodsInfo.coverImg" class="head-left" />
          <div class="head-right">
            <p class="goodsName line_ellipsis">{{goodsInfo.goodsName}}</p>
            <div class="head_title flex flex-pack-justify">
              <span class="price">{{goodsSku.salesPrice||goodsInfo.salePrice}}积分</span>
              <span class="number">库存：{{goodsSku.stock||(goodsSku.stock==0?0:goodsInfo.stock)}}</span>
            </div>
            <img src="/static/images/store/close.png" @click="closeDialog" class="close" alt />
          </div>
        </div>

        <div class="rule-box flex align-center" v-for="(item,index) of skuSpecList" :key="index">
          <p class="rule-title">{{item.specName}}</p>
          <div class="rule-item-box">
            <div
              v-for="(children,p) of item.skuSpecValueList"
              :class="{'rule-item':true,'active':children.isSelect}"
              :key="p"
              @click="selectRule(index,p,children)"
              :data-parent="index"
              :data-children="p"
            >{{children.specName}}</div>
          </div>
        </div>
        <!-- disabled:!children.isDisable.disable -->

        <div class="number-box">
          <span class="number-title">数量</span>
          <van-stepper
            v-model="goodsCount"
            :max="goodsSku.stock||(goodsSku.stock==0?0:goodsInfo.stock)"
            @change="goodsCountChange"
          ></van-stepper>
        </div>
        <div class="footer" style="border-top:1px solid #e6e6e6;">
          <button class="btn" @click="handleConfirm">确定</button>
        </div>
      </div>
      <!-- </van-popup> -->
    </div>
    <!-- 底部购买 -->
    <div class="footer">
      <button class="btn" @click="handleDetails">立即购买</button>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import { mapGetters } from "vuex";
import { queryGoddsDetails, getRichText, getBannerDetails } from "@/api/api";
export default {
  props: {},
  data() {
    return {
      show: false, // 弹框显示
      swiperIndex: 1,
      skus: [], // 选中的组合
      richText: "",
      goodsInfo: {
        bannerImgPaths: [
          // '/static/images/timg.png',
          // '/static/images/timg1.png',
          // '/static/images/timg2.png'
        ],
        goodsName: "",
        actualSales: 0,
        salePrice: 0,
        id: 0,
        stock: 0,
        coverImg: "/static/images/timg1.png"
      },
      goodsSku: {}, // 选中组合的商品信息
      isBuy: false,
      goodsId: "",
      goodsCount: 1, // 购买商品的数量
      // 规格
      skuSpecList: [],
      goodsSkuDetailList: [],
      goodsSpecRelationList: [],
      id: 0,
      height: 375
    };
  },
  /**监听离开页面事件 */
  onUnload() {
    this.show = false;
    Object.assign(this.$data, this.$options.data());
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  mounted() {
    // 可以将当前状态的data重置为初始状态
    Object.assign(this.$data, this.$options.data());
    this.goodsId = this.$root.$mp.query.classifyId;
    this.height = wx.getSystemInfoSync().windowWidth;
    console.log("商品详情id", this.goodsId);
    if (this.goodsId) {
      this.queryGoddsDetails(this.goodsId);
    }
  },
  watch: {},
  methods: {
    // 商品轮播
    swiperChange(e) {
      this.swiperIndex = e.mp.detail.current + 1;
    },
    /**
     * 弹出商品规格
     */
    handleDetails() {
      /** 判断用户是否实名认证和风险测评 */
      if (this.userInfo) {
        if (!this.userInfo.reg) {
          wx.showToast({
            title: "请先注册",
            icon: "none",
            duration: 1000
          });
          setTimeout(() => {
            wx.navigateTo({
              url: "/pages/index/children/register/main"
            });
          }, 1000);
          return;
        }
        if (this.userInfo.identity === "USER") {
          if (!this.userInfo.realName) {
            wx.showToast({
              title: "请先实名认证",
              icon: "none",
              duration: 1000
            });
            setTimeout(() => {
              wx.navigateTo({
                url: "/pages/PersonalCenter/userChildren/verified/main"
              });
            }, 1000);
            return;
          }
          if (!this.userInfo.passRisk) {
            wx.showToast({
              title: "请先风险测评",
              icon: "none",
              duration: 1000
            });
            setTimeout(() => {
              wx.navigateTo({
                url:
                  "/pages/PersonalCenter/userChildren/evaluation/startEvaluation/main"
              });
            }, 1000);
          } else {
            this.show = true;
            this.isBuy = true;
          }
        } else {
          this.show = true;
          this.isBuy = true;
          // wx.showToast({
          //   title: "理财师暂无权限购买商品",
          //   icon: "none",
          //   duration: 1000
          // });
        }
      }
    },
    /**
     * 关闭分类弹框
     */
    showDialog() {
      this.show = true;
    },
    closeDialog() {
      this.show = false;
    },
    /**
     * 跳到确认订单页面
     */
    async handleConfirm() {
      if (!this.goodsSku.specIds) {
        wx.showToast({
          title: "请选择商品规格",
          icon: "none",
          duration: 2000
        });
        return;
      }
      if (this.goodsCount > this.goodsSku.stock) {
        wx.showToast({
          title: "商品库存不足！",
          icon: "none",
          duration: 2000
        });
        return;
      }
      if (this.isBuy) {
        let items = [
          {
            goodsId: this.goodsId, // 商品编号
            goodsSkuNo: this.goodsSku.skuNo, // sku编号
            saleQuantity: this.goodsCount // 数量
          }
        ];
        let obj = {};
        obj.items = items;
        let info = { ...this.goodsInfo, ...this.goodsSku };
        info.quantity = this.goodsCount;
        info.isCheck = false;
        info.goodsName = this.goodsInfo.goodsName;
        // this.noPayOrder([info]);
        wx.setStorageSync("info", [info]);
        // wx.navigateTo({ url: "/pages/store/children/confirmOrder/main" });

        // 跳转路径待完善
        wx.navigateTo({
          url: `/pages/store/children/confirmOrder/main?id=${this.goodsId}`
        });

        // await orderCalculate(obj).then(res => {
        //   if (!res.code) {
        //     wx.navigateTo({ url: '/pages/generateOrder/main' });
        //   }
        // });
      }
    },
    /**
     * 查询商品详情
     */
    async queryGoddsDetails(goodsId) {
      // wx.showLoading({
      //   title: "加载中",
      //   mask: true
      // });
      let data = await queryGoddsDetails({ id: goodsId });
      // wx.hideLoading();
      // console.log("data:", data);
      if (!data.code) {
        let obj = {
          bannerImgPaths: data.bannerImgPaths,
          goodsName: data.goodsName,
          actualSales: data.actualSales,
          salePrice: data.salePrice,
          id: data.id,
          stock: data.stock,
          coverImg: data.coverImg
        };
        this.goodsSpecRelationList = data.goodsSpecRelationList.reverse();
        this.goodsSkuDetailList = data.goodsSkuDetailList;
        let stock = 0;
        for (let item of this.goodsSkuDetailList) {
          stock += item.stock;
        }
        obj.stock = stock;
        console.log(obj, "objobjobjobj");
        this.goodsInfo = obj;
        this.loadDetail();
        this.getRichText(data.richId);
      } else {
        wx.showToast({
          title: data.description,
          icon: "none",
          duration: 3000
        });
      }
    },
    /**
     * 富文本
     */
    async getRichText(id) {
      let data = await getRichText({ id });
      if (data.content) {
        this.richText = data.content;
      }
    },
    /**
     * 处理选择商品的数量
     */
    goodsCountChange(e) {
      this.goodsCount = e.mp.detail;
    },
    /**
     * 处理规格数据
     */
    loadDetail() {
      const skuSpecList = [];
      this.goodsSpecRelationList.forEach(item => {
        if (item.pid == 0) {
          item.skuSpecValueList = [];
          skuSpecList.push(item);
        }
      });
      // goodsInfo.stock
      skuSpecList.forEach((item, index) => {
        this.goodsSpecRelationList.forEach(relItem => {
          if (relItem.pid == item.specId) {
            relItem.isDisable = {
              specId: relItem.specId,
              disable: false
            };
            item.skuSpecValueList.push({ ...relItem, index });
          }
        });
      });
      /**
       * 过滤掉有规格名没有规格值的数据
       */
      let arr = skuSpecList.filter(item => {
        return item.skuSpecValueList && item.skuSpecValueList.length > 0;
      });
      this.initDisable(arr);
      this.skuSpecList = arr;
    },
    /**
     * 此处初始化可选状态
     */
    initDisable(skuSpecList) {
      for (let parentItem of skuSpecList) {
        for (let childrenItem of parentItem.skuSpecValueList) {
          this.goodsSkuDetailList.map(item => {
            let ids = item.specIds.split(",");
            for (let id of ids) {
              if (id == childrenItem.specId) {
                if (item.isEnabled) {
                  childrenItem.isDisable = { specId: id, disable: true };
                }
              }
            }
          });
        }
      }
    },
    /**
     * 选择规则
     */
    selectRule(index, p, children) {
      console.log(index, p, children);
      let parentIndex = index;
      let childrenIndex = p;
      // eslint-disable-next-line standard/computed-property-even-spacing
      let targetItem = this.skuSpecList[parentIndex].skuSpecValueList[
        childrenIndex
      ];
      if (!targetItem.isDisable.disable) return;
      this.initDisable(this.skuSpecList);
      this.skuSpecList[parentIndex].skuSpecValueList.map((item, index) => {
        if (index == childrenIndex) {
          item.isSelect = !item.isSelect;
        } else {
          item.isSelect = false;
        }
      });
      /**
       * 如果已经存在选中的规格就替换否则添加
       */
      let skuIndex = -1;
      for (let i = 0; i < this.skus.length; i++) {
        let sku = this.skus[i];
        if (sku.pid == targetItem.pid) {
          skuIndex = i;
        }
      }
      if (skuIndex == -1) {
        this.skus.push(targetItem);
      } else {
        if (targetItem.isSelect) {
          this.skus.splice(skuIndex, 1, targetItem);
        } else {
          this.skus.splice(skuIndex, 1);
        }
      }

      for (let targetItem of this.skus) {
        this.goodsSkuDetailList.map(item => {
          let ids = item.specIds.split(",");
          for (let id of ids) {
            if (id == targetItem.specId) {
              if (!item.isEnabled) {
                let i = ids.indexOf(id);

                ids.splice(i, 1);
                for (let mId of ids) {
                  for (let pSku of this.skuSpecList) {
                    for (let cSku of pSku.skuSpecValueList) {
                      if (mId == cSku.specId) {
                        // 不可点击
                        cSku.isDisable = {
                          specId: cSku.specId,
                          disable: false
                        };
                      } else {
                        // 可以点击
                        // cSku.isDisable = true;
                        for (let item of this.skus) {
                          // eslint-disable-next-line no-self-compare
                          if (item.specId !== item.specId) {
                            cSku.isDisable = {
                              specId: cSku.specId,
                              disable: true
                            };
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        });
      }
      /**
       * 判断规格是否全部选择完
       */
      if (this.skus.length == this.skuSpecList.length) {
        let specIds = [];
        for (let sku of this.skus) {
          specIds.push(sku.specId + "");
        }
        if (specIds.length > 0) {
          for (let item of this.goodsSkuDetailList) {
            let isEqual = true;
            let specArr = item.specIds.split(",");
            // 比如 188,120 和 120,188 是代表同一个规格 逻辑上是相等
            for (let id of specIds) {
              let index = specArr.indexOf(id);
              if (index == -1) {
                isEqual = false;
                break;
              }
            }
            if (isEqual) {
              this.goodsSku = item;
              break;
            }
          }
        } else {
          this.goodsSku = {};
        }
      } else {
        this.goodsSku = {};
      }
      let arr = [...this.skuSpecList];
      this.skuSpecList = arr;
    }
  },
  components: {}
};
</script>

<style scoped lang="less">
// 商品图片展示部分
.page {
  position: fixed;
  height: 100%;
  overflow: hidden;
}
.page1 {
  position: static;
  height: auto;
  overflow: visible;
}
.show {
  border-radius: 8px 8px 0px 0px;
  background: rgba(0, 0, 0, 0.4);
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 99;
}
.header {
  width: 375px;
  height: 375px;
  background-color: #ffffff;
  position: relative;
  .position {
    position: absolute;
    bottom: 10px;
    right: 10px;
    padding: 0 8px;
    border-radius: 24px;
    display: inline-block;
    background: rgba(0, 0, 0, 0.2);
    font-size: 14px;
    font-family: PingFangSC;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
  }
  .swiper-box {
    width: 100%;
    height: 100%;
    .swiper-item {
      width: 100%;
      height: 100%;
      .image-box {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;

        .slide-image {
          // height: 375px;
          width: 100%;
        }
      }
    }
  }
}

// 主体部分
.details {
  padding: 20px 15px;

  .det-title {
    color: #081020;
    font-size: 16px;
    font-family: PingFangSC;
    font-weight: 700;
    line-height: 24px;
    margin-bottom: 20px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .det-mun {
    height: 25px;
    font-family: PingFangSC;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .det-left {
      color: #f45247;
      font-size: 24px;
      font-weight: 800;
    }

    .det-right {
      color: #868991;
      font-size: 14px;
      font-weight: 400;
    }
  }
}

.photo {
  margin: 0 auto;
  width: 100%;
  // background-color: skyblue;
  // padding-bottom: 100px;
  padding: 0 15px 100px;
  box-sizing: border-box;
}
.goodsName {
  font-size: 14px;
  color: rgba(2, 6, 4, 1);
  padding-right: 20px;
}
// 商品规格
.speci-content {
  width: 100%;
  max-height: 400px;
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  position: absolute;
  bottom: 0;
  padding: 15px;
  box-sizing: border-box;
  overflow-y: scroll;
  padding-bottom: 54px;
  .head-box {
    width: 100%;
    height: 120px;
    display: flex;
    align-items: center;
    flex-direction: row;
    border-bottom: 1px solid #e6e6e6;
    box-sizing: border-box;
    padding-bottom: 20px;
  }
  .head-left {
    width: 90px;
    height: 90px;
    border-radius: 4px;
  }
  .head-right {
    height: 90px;
    flex: 1;
    padding-left: 15px;
    display: flex;
    // align-items: flex-start;
    // justify-content: center;
    flex-direction: column;
    justify-content: space-between;

    position: relative;
    .price {
      font-size: 14px;
      font-weight: 700;
      color: #f45247;
    }
    .number {
      font-size: 14px;
      font-weight: 400;
      color: rgba(134, 137, 145, 1);
      line-height: 24px;
    }
    .close {
      position: absolute;
      display: inline-block;
      width: 15px;
      height: 15px;
      // background: url("/static/images/store/close.png") no-repeat center;
      // background-size: contain;
      right: 0px;
      top: 0px;
      z-index: 999;
    }
  }
  .rule-box {
    padding-top: 15px;
    .rule-title {
      width: 50px;
      font-size: 14px;
      font-family: PingFangSC;
      font-weight: 400;
      color: rgba(8, 16, 32, 1);
    }
    .rule-item-box {
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      box-sizing: border-box;
      justify-content: flex-start;
      .rule-item {
        padding: 5px 13px;
        background: #fff;
        border-radius: 2px;
        box-sizing: border-box;
        font-size: 12px;
        font-family: PingFangSC;
        font-weight: 400;
        color: rgba(82, 87, 98, 1);
        text-align: center;
        border: 1px solid #e6e7e3;
        margin-left: 15px;
      }
      .active {
        background: #fff;
        border: 1px solid #187798;
        color: #187798;
      }
      .disabled {
        color: rgba(82, 87, 98, 0.5);
        background: rgba(250, 250, 250, 0.3);
        border: 1px solid rgba(250, 250, 250, 1);
      }
    }
  }
  .number-box {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 15px;
    border-bottom: 1px solid #e6e6e6;
    padding-bottom: 20px;
    box-sizing: border-box;
    margin-bottom: 48px;
    .number-title {
      font-size: 14px;
      font-family: PingFangSC;
      font-weight: 400;
      color: rgba(8, 16, 32, 1);
    }
  }
}

// 底部购买
.footer {
  height: 54px;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  padding: 6px 15px;
  box-sizing: border-box;
  background-color: #fff;

  .btn {
    line-height: 42px;
    background-color: #187798;
    color: rgba(255, 255, 255, 1);
    font-weight: 700;
    font-size: 15px;
    height: 100%;
  }
}
</style>
